/**
 *
 *
 *
 */

//
//<div data-grid="easyui" data-url="">
//  <button type="button" class="btn search-btn" data-method="export" data-url="export.json"><i class="fa fa-search"></i>&nbsp;导出&nbsp;</button>
//  <form action="list.json">
//  <button type="button" class="btn search-btn" data-method="search"><i class="fa fa-search"></i>&nbsp;查询&nbsp;</button>
//  <button type="button" class="btn search-btn" data-method="clear"><i class="fa fa-trash"></i>&nbsp;清空&nbsp;</button>
//  </form>
//  <table class="easyui-datagrid">
//    <thead>
//      <tr>
//        <th data-options="field:'id',checkbox:true">选择</th>
//        <th data-options="field:'demandName',width:200">需求名称</th>
//        <th data-options="field:'demandNumber',width:100">需求编号</th>
//        <th data-options="field:'demandAdminName',width:100">需求管理员</th>
//        <th data-options="field:'processStatus',width:100">需求状态</th>
//        <th data-options="field:'demandHomeDomain',width:100">需求归属域</th>
//        <th data-options="field:'demandUrgency',width:100">需求紧急程度</th>
//        <th data-options="field:'demandProposedTime',width:100">申请日期</th>
//      </tr>
//    </thead>
//  </table>
//</div>


define(function (require, exports, module) {

    /* 每0.5s检测窗口是否关闭，关闭触发回调 */
    var openwindow = function (winOpenResult, callback) {
        var timer; //定时器
        var timingTestfun = function () { //定时检测程序
            if (winOpenResult.closed) {// 弹出窗口被关闭
                try {
                    callback();
                } finally {
                    if (timer) {
                        window.clearInterval(timer);
                        time = null;
                    }
                }
            }
        };
        if (!timer) {
            timer = window.setInterval(timingTestfun, 500);
        }
    };

    /* 打开窗口，全屏参数 */
    var defaultScreenLocation = 'width=' + (window.screen.availWidth - 10) + ',height=' + (window.screen.availHeight - 30) + "top=0,left=0,menubar=yes,resizable=yes,scrollbars =yes";

    /* 下载文件工具函数 */
    var exportFile = function (url) {
        var iframe;
        (function () {
            if (iframe) {
                iframe.src = url;
            } else {
                iframe = document.createElement('iframe');
                iframe.src = url;
                iframe.style.display = "none";
                document.body.appendChild(iframe);
            }
        })();
    };

    /* easyui data grid 定制缺省配置 */
    var dataGridDefaultConfig = {
        url: 'getList.json',
        method: "GET",
        rownumbers: false,
        striped: false,
        checkOnSelect: true,
        fitColumns: true,
        nowrap: true,
        height: 385,
        loadMsg: "数据加载中...",
        pagination: true,
        pageSize: 10,
        pageList: [10],
        onBeforeLoad: function (conditions) {
            conditions['page.currentPage'] = conditions.page;
            conditions['page.pageSize'] = conditions.rows;
            delete conditions.page;
            delete conditions.rows;
        },
        loadFilter: function (result) {
            if (result.result) {
                return result.data;
            } else {
                EasyuiUtil.Messager.showError(result.message);
            }
        }
    };

    var dataGridDefaultConfig = $.extend({}, dataGridDefaultConfig, module.config());

    /* 分页查询 */
    var Grid = function () {
        this.el = $('[data-grid="easyui"]') /*  包含查询条件form和分页grid的div或body */
        this.form = $('form', this.el).submit(function () {
            return false
        }) /* 查询条件from */
        this.grid = $('table.easyui-datagrid', this.el) /* 分页grid */

        /* 初始化data-grid */
        if (this.columns) {// 准备Grid的字段格式化函数
            for (field in this.columns) {
                var option = this.grid.datagrid("getColumnOption", field);
                if (option) {
                    var formatter = this.columns[field].formatter;
                    if (formatter)
                        option.formatter = formatter;
                }
            }
        }
        var gridConfig = $.extend({}, dataGridDefaultConfig, {queryParams: this.queryParam()});
        this.grid.datagrid(gridConfig)
            .datagrid("getPager")
            .pagination({
                beforePageText: '第',
                afterPageText: '页&nbsp;&nbsp;&nbsp;&nbsp;共 {pages} 页',
                displayMsg: '当前显示 {from} - {to} 条记录   共 {total} 条记录'
            })

        //准备按钮单击事件
        var context = this
        this.el.delegate('button[data-method]', 'click', function () {
            var methodName = $(this).data('method')
            if (methodName && $.isFunction(context.methods[methodName])) {
                context.methods[methodName].apply(context, arguments);
            } else {
                throw new Error('button data-method属性可能为空，或methods属性中不存在对应函数')
            }
        })
    }

    /* 分页grid的columns的formatter 和对应的event */
    Grid.prototype.columns = {
        //  field : {formatter: formatter, event: event }
    }

    /* 下载文件缺省地址 */
    var download = module.config().contextPath ? module.config().contextPath + "dynamic/commons/download" : "download";

    Grid.prototype.methods = {
        search: function () { // 查询
            this.grid.datagrid('reload', this.queryParam());
        },

        clear: function () { // 清理查询条件，并重新查询
            this.form.each(function () {
                this.reset()
            });
            this.grid.datagrid('load', this.queryParam());
        },

        exportfile: function (event) { // 导出文件
            EasyuiUtil.Messager.showWaiting();

            var url = $(event.target).data('url') ? $(event.target).data('url') : "make/exportfile";

            this.post(url).always(function () {
                EasyuiUtil.Messager.closeWaiting();
            })
                .done(function (r) {
                    if (r.result) {
                        exportFile(download + "?" + $.param({filepath: r.message}));
                    }
                })
                .fail(function () {
                    EasyuiUtil.Messager.showError("生成文件失败，网络原因或服务故障，请重试或联系管理员！");
                });
        },

        download: function (event) { // 下载文件
            var filepath = $(event.target).data('filepath');

            if (filepath) {
                exportFile(download + "?" + $.param({filepath: filepath}));
            } else {
                throw new Error('data-filepath don\'t set');
            }
        }
    }

    /* 打开新窗口，当新窗口关闭时刷新grid */
    Grid.prototype.windowOpen = function (url, title, location) {
        var l = $.type(location) === "string" && location ? location : defaultScreenLocation;
        openwindow(window.open(url, "", l), $.proxy(function () {
            this.grid.datagrid('reload', this.queryParam());
        }, this));
    }

    /* ajax get json */
    Grid.prototype.get = function (url) {
        return $.ajax({url: url, type: "get", dataType: "json", data: this.queryParam(), cache: false});
    }

    /* ajax post json */
    Grid.prototype.post = function (url) {
        return $.ajax({url: url, type: "post", dataType: "json", data: this.queryParam(), cache: false});
    }

    /* 获得form的查询参数 */
    Grid.prototype.queryParam = function () {
        var array = this.form.serializeArray();
        var _queryParams = {};
        for (var i = 0; i < array.length; i++) {
            _queryParams[array[i].name] = array[i].value.trim();
        }
        return _queryParams;
    }

    /**
     * 设置 grid的 column的特殊格式函数，和扩展事件
     * @param columns
     */
    Grid.columns = function (columns) {
        for (var field in (columns || {})) {
            this.prototype.columns[field] = $.extend({}, this.prototype.columns[field], columns[field])
        }
    }

    /**
     * 添加新的button
     * @param methods
     */
    Grid.methods = function (methods) {
        this.prototype.methods = $.extend({}, this.prototype.methods, methods)
    }

    /**
     * 实例化Grid，同时返回Grid columns中对应的事件
     * @returns {___anonymous6747_6748}
     */
    Grid.events = function () {
        var grid = new this.prototype.constructor();

        var columns = grid.columns || {}

        var result = {}
        for (var field in columns) {
            var column = columns[field]
            if ($.isFunction(column.event)) {
                result[field] = $.proxy(column.event, grid);
            }
        }

        return result;
    };

    return Grid;
})